﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VsxFactory.ExtensionManager.Providers;
using Microsoft.VisualStudio.ExtensionsExplorer;

namespace VsxFactory.ExtensionManager
{
    /// <summary>
    /// This tree node lists all packages from a fixed repository.
    /// </summary>
    internal class UpdateTreeNode : PackagesTreeNodeBase
    {

        private readonly IPackageRepository _repository;
        private readonly string _category;
        Microsoft.VisualStudio.ExtensionManager.IVsExtensionManager _extensionManager;

        public UpdateTreeNode(Microsoft.VisualStudio.ExtensionManager.IVsExtensionManager extensionManager, PackagesProviderBase provider, string category, IVsExtensionsTreeNode parent, IPackageRepository repository) :
            base(parent, provider, repository)
        {

            if (category == null)
            {
                throw new ArgumentNullException("category");
            }
            if (repository == null)
            {
                throw new ArgumentNullException("repository");
            }

            _category = category;
            _repository = repository;
            _extensionManager = extensionManager;
        }

        public override string Name
        {
            get
            {
                return "Updates for " + _category;
            }
        }

        public override IQueryable<DataServicePackage> GetPackages()
        {
            List<DataServicePackage> results = new List<DataServicePackage>();
            var installedExtension = _extensionManager.GetInstalledExtensions();
            foreach (var package in _repository.GetPackages())
            {
                Version v;
                if (Version.TryParse(package.Version, out v))
                {
                    if (installedExtension.Any(p => p.Header.Name.Equals(package.Name, StringComparison.OrdinalIgnoreCase) && p.Header.Version < v))
                        results.Add(package);
                }
            }
            return results.AsQueryable();
        }
    }
}
